package com.juku2024.juku.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.animation.ObjectAnimator
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.juku2024.juku.R
import com.juku2024.juku.tools.LogC



class VideoScreenView(context: Context, attributeSet: AttributeSet) : ConstraintLayout(context, attributeSet) {

    // 是否投屏正在播放
    private var isPlaying = false
    // 是否正在显示投屏View
    private var isShowingDes = false
    // 是否连接上设备
    private var isConnectDevices = false
    // 播放地址
    private var url: String? = null
    // 视频名称
    private var title: String? = null

    private val play: View
    private val seekBar: SeekBar
    private val tvVideoEndTime: TextView
    private val tvVideoStartTime: TextView
    private val dlanRoot: ViewGroup
    private val controller: View

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.view_video_screen, this, true)
        view.setBackgroundColor(Color.BLACK)
        view.isFocusable = true
        view.isClickable = true

        play = view.findViewById(R.id.play)
        seekBar = view.findViewById(R.id.seekBar)
        tvVideoEndTime = view.findViewById(R.id.tvVideoEndTime)
        tvVideoStartTime = view.findViewById(R.id.tvVideoStartTime)
        dlanRoot = view.findViewById(R.id.dlanRoot)
        controller = view.findViewById(R.id.controller)

        play.setOnClickListener {
            if (isPlaying) {
//                LelinkSourceSDK.getInstance().pause()
            } else {
//                LelinkSourceSDK.getInstance().resume()
            }
        }

        seekBar.setOnSeekBarChangeListener(object: OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
//                    LelinkSourceSDK.getInstance().seekTo(progress / 1000)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        })
    }


    fun showScreen(title: String?, url: String?, duration: Long, currentPosition: Long) {
        this.title = title
        this.url = url
        tvVideoEndTime.text = getHMSTime(duration)
        tvVideoStartTime.text = getHMSTime(currentPosition)
        seekBar.max = duration.toInt()
        seekBar.progress = currentPosition.toInt()
        dlanRoot.removeAllViews()
//        LelinkSourceSDK.getInstance()
//            .setSdkInitInfo(context , "21742", "67016cb27520aef377d452e276b14239")
//            .easyPush(dlanRoot)
//        LelinkSourceSDK.getInstance().setEasyCastListener(this)
        controller.visibility = View.GONE
        isConnectDevices = true
        show()
    }

//    /**
//     * 如果没有触发此回调，则表示此次未搜索到设备或用户未投屏
//     * @param lelinkServiceInfo
//     * @return
//     */
//    override fun onCast(p0: LelinkServiceInfo?): EasyCastBean {
//        LogC.e("投屏 -> onCast")
//        isConnectDevices = true
//        val bean = EasyCastBean()
//        bean.url = url //实际需要投屏的url
//        return bean
//    }
//
//    /**
//     * 如果投屏失败，在搜索页面关闭的时候，会触发回调
//     * @param lelinkServiceInfo
//     * @param easyCastBean
//     * @param what
//     * @param extra
//     */
//    override fun onCastError(p0: LelinkServiceInfo?, p1: EasyCastBean?, p2: Int, p3: Int) {
//        isPlaying = false
//        isConnectDevices = false
//    }
//
//    /**
//     * 推送成功
//     * @param lelinkServiceInfo
//     * @param easyCastBean
//     */
//    override fun onCastLoading(p0: LelinkServiceInfo?, p1: EasyCastBean?) {
//    }
//    /**
//     * 暂停
//     * @param lelinkServiceInfo
//     * @param easyCastBean
//     */
//    override fun onCastPause(p0: LelinkServiceInfo?, p1: EasyCastBean?) {
//        viewPlay.setBackgroundResource(R.drawable.icon_video_play)
//        isPlaying = false
//    }
//
//    override fun onCastStart(p0: LelinkServiceInfo?, p1: EasyCastBean?) {
//        viewPlay.setBackgroundResource(R.drawable.icon_video_pause)
//        isPlaying = true
//    }
//
//    /**
//     * 收端播放结束，如果需要实现下一集，可在之后的onCast回调中提供播放信息
//     * @param lelinkServiceInfo
//     * @param easyCastBean
//     */
//    override fun onCastCompletion(p0: LelinkServiceInfo?, p1: EasyCastBean?) {
//        viewPlay.setBackgroundResource(R.drawable.icon_video_play)
//        isPlaying = false
//    }
//
//    override fun onCastPositionUpdate(p0: LelinkServiceInfo?, p1: EasyCastBean?, p2: Long, p3: Long) {
//        tvVideoStartTime.text = getHMSTime(p3 * 1000)
//        seekBar.progress = (p3 * 1000).toInt()
//    }
//    /**
//     * 搜索退出播放，不同于 onCastCompletion，此时需要恢复APP视频播放
//     * @param lelinkServiceInfo
//     * @param easyCastBean
//     */
//    override fun onCastStop(p0: LelinkServiceInfo?, p1: EasyCastBean?) {
//        viewPlay.setBackgroundResource(R.drawable.icon_video_play)
//        isPlaying = false
//    }
//
//    override fun onDismiss() {
//        LogC.e("投屏 -> onDismiss....")
//        if (isConnectDevices) {
//            isConnectDevices = false
//            controller.visibility = View.VISIBLE
//        }
//    }


    private fun show() {
        isShowingDes = true
        val animator: ObjectAnimator = ObjectAnimator.ofFloat(this, "translationY", 2000f, 0f)
        animator.duration = 200
        animator.interpolator = DecelerateInterpolator()
        animator.start()
    }

    fun isShowing(): Boolean {
        return isShowingDes
    }

    fun hide() {
        isPlaying = false
        isShowingDes = false
        isConnectDevices = false
        controller.visibility = View.GONE
        val animator: ObjectAnimator = ObjectAnimator.ofFloat(this, "translationY", 0f, 2000f)
        animator.duration = 200
        animator.interpolator = AccelerateInterpolator()
        animator.start()

        release()
    }


    fun release(){
        LogC.e("DLNAManager -> 释放...")
        try {
//            LelinkSourceSDK.getInstance().unBindSdk()
        } catch (e:Exception) {
            e.printStackTrace()
        }
    }

 

    /**
     * long值转换时分秒
     */
    private fun getHMSTime(time: Long): String {
        val timeStr: String?
        val hour: Long?
        var minute: Long?
        val second: Long?
        if (time <= 1000)
            return "0:00:00"
        else {
            val secondTime = time / 1000
            minute = secondTime / 60
            if (minute < 60) {
                second = secondTime % 60
                timeStr = "0:" +unitFormat(minute) + ":" + unitFormat(second)
            } else {
                hour = minute / 60
                if (hour > 99)
                    return "99:59:59"
                minute %= 60
                second = secondTime - (hour * 3600) - (minute * 60)
                timeStr = hour.toString() + ":" + unitFormat(minute) + ":" + unitFormat(second)
            }
        }
        return timeStr
    }

    private fun unitFormat(i: Long): String {
        return if (i in 0..9)
            "0$i"
        else
            i.toString()
    }


}